package com.heima.article.service.impl;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.heima.article.client.HaviorFeign;
import com.heima.article.client.UserFeign;

import com.heima.article.dto.*;
import com.heima.article.entity.*;

import com.heima.article.mapper.ApArticleMapper;
import com.heima.article.service.*;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.common.dto.ResponseResult;
import com.heima.common.entity.User;
import com.heima.common.enums.AppHttpCodeEnum;
import com.heima.common.util.AppThreadLocal;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchRestTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * <p>
 * 文章信息表，存储已发布的文章 服务实现类
 * </p>
 *
 * @author mcm
 * @since 2022-06-23
 */
@Service
public class ApArticleServiceImpl extends ServiceImpl<ApArticleMapper, ApArticle> implements IApArticleService {
    @Autowired
    private IApArticleContentService contentService;

    @Autowired
    private IstaticLoading staticLoading;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private ApArticleSearchRepository searchRepository;

    @Autowired
    private ElasticsearchRestTemplate restTemplate;

    @Override
//    @Async
    public ResponseResult<Long> saveArticle(ArticleDto dto) {
//        创建文章
        ApArticle apArticle = new ApArticle();
        BeanUtils.copyProperties(dto,apArticle);
//        判断是否存在id
        if (dto.getId() == null){
            apArticle.setCreatedTime(new Date());
//            保存文章
            this.save(apArticle);
//            保存文章内容
            ApArticleContent apArticleContent = new ApArticleContent();
           apArticleContent.setArticleId(apArticle.getId());
           apArticleContent.setContent(dto.getContent());
           contentService.save(apArticleContent);

//           在es里同步
            ApArticleSearch apArticleSearch = new ApArticleSearch();
            BeanUtils.copyProperties(apArticle,apArticleSearch);
            searchRepository.save(apArticleSearch);

//           静态加载
            System.out.println("开始静态加载");
           staticLoading.staticLoading(apArticle,dto.getContent());
           return ResponseResult.okResult(apArticle.getId());
        }
//        修改文章
        this.updateById(apArticle);
//        保存文章内容

        LambdaUpdateWrapper<ApArticleContent> update = new LambdaUpdateWrapper<>();
        update.eq(ApArticleContent::getArticleId,apArticle.getId());
        update.eq(ApArticleContent::getContent,dto.getContent());
        contentService.update(update);

//           在es里同步
        ApArticleSearch apArticleSearch = new ApArticleSearch();
        BeanUtils.copyProperties(apArticle,apArticleSearch);
        searchRepository.deleteById(apArticle.getId());
        searchRepository.save(apArticleSearch);

//        静态加载
        staticLoading.staticLoading(apArticle,dto.getContent());
        return ResponseResult.okResult(apArticle.getId());
    }

    @Override
    public ResponseResult load(ArticleHomeDto dto, int type) {
//        判断是不是首页，如果是从redis查询数据
        if (dto.getLoaddir() == 1){
            String key = "hot_article_"+dto.getChannelId();
            Set<String> strings = redisTemplate.opsForZSet().reverseRange(key, 0, dto.getSize() - 1);
            List<ApArticle> apArticles = new ArrayList<>();
            for (String string : strings) {
                ApArticle apArticle = JSON.parseObject(string, ApArticle.class);
                apArticles.add(apArticle);
            }
//        查询数据是否大于等于size
            if (dto.getSize() == apArticles.size()){
                return ResponseResult.okResult(apArticles);
            }
        }

//        如果不大于 ，就从数据库中查询

//        查询所属频道
        LambdaQueryWrapper<ApArticle> query = new LambdaQueryWrapper<>();
        if (dto.getChannelId() != 0) {
            query.eq(ApArticle::getChannelId, dto.getChannelId());
        }
//            过滤已删除和下架的文章
        query.eq(ApArticle::getIsDown,false);
        query.eq(ApArticle::getIsDelete,false);
//        判断最新还时更多
        if (type == 0){
            query.lt(ApArticle::getPublishTime,dto.getMinTime());
        }else {
            query.ge(ApArticle::getPublishTime,dto.getMaxTime());
        }
        query.orderByDesc(ApArticle::getPublishTime);
        IPage<ApArticle> page = new Page<>(1,dto.getSize());

        IPage<ApArticle> page1 = this.page(page, query);
        return ResponseResult.okResult(page1.getRecords());
    }

    @Override
    public ResponseResult info(ArticleInfoDto dto) {
//        查新文章
        ApArticle apArticle = this.getById(dto.getArticleId());
//        查询
        LambdaQueryWrapper<ApArticleContent> query = new LambdaQueryWrapper<>();
        query.eq(ApArticleContent::getArticleId,dto.getArticleId());
        ApArticleContent one = contentService.getOne(query);
        Map<String,Object> map  = new HashMap<>();
        map.put("config",apArticle);
        map.put("content",one);
        return ResponseResult.okResult(map);
    }
    @Autowired
    private IApCollectionService collectionService;
    @Override
    public ResponseResult collect(CollectionBehaviorDto dto) {

        // 获取当前登录的用户
        User user = AppThreadLocal.get();
        if (user == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        // 构建收藏记录
        ApCollection collection = new ApCollection();
        collection.setEntryId(user.getUserId());
        collection.setArticleId(dto.getArticleId());
        collection.setCollectionTime(new Date());
        // 判断是否已经有记录
        LambdaQueryWrapper<ApCollection> query = new LambdaQueryWrapper<>();
        query.eq(ApCollection::getArticleId, dto.getArticleId());
        query.eq(ApCollection::getEntryId, user.getUserId());
        ApCollection one = collectionService.getOne(query);
        if (one == null) {
            if (dto.getOperation() == 0) {
                collectionService.save(collection);
            }
        } else {
            if (dto.getOperation() == 1) {
                collectionService.removeById(one.getId());
            }
        }
        return ResponseResult.okResult();
    }
    @Autowired
    private HaviorFeign haviorFeign;
    @Autowired
    private UserFeign userFeign;
    @Autowired
    private IApAuthorService apAuthorService;

    /**
     * app文章关系实现
     * @param dto
     * @return
     */
    @Override
    public ResponseResult LoadArticle(ArticleInfoDto dto) {
        boolean isfollow = false;
        boolean islike = false;
        boolean isnulike = false;
        boolean iscollection = false;

        User user = AppThreadLocal.get();

//       查询点赞记录
        LikesBehaviorDto likeDto = new LikesBehaviorDto();
        likeDto.setEquipmentId(dto.getEquipmentId());
        if (user != null){
            likeDto.setUserId(user.getUserId());
        }
        likeDto.setArticleId(dto.getArticleId());
        ResponseResult<ApLikesBehavior> likes = haviorFeign.getLikes(likeDto);
        if (likes.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())){
            ApLikesBehavior data = likes.getData();
            if (data != null && data.getOperation() == 0) {
                islike = true;
                System.out.println("查询到点赞记录");
            }
        }
//        查询不喜欢
        UnLikesBehaviorDto unLikesBehaviorDto = new UnLikesBehaviorDto();
        BeanUtils.copyProperties(dto,unLikesBehaviorDto);
        if (user == null){
            unLikesBehaviorDto.setEquipmentId(dto.getEquipmentId());
        }
        ResponseResult<ApUnlikesBehavior> unlike = haviorFeign.getUnlike(unLikesBehaviorDto);
        if (unlike.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())){
            ApUnlikesBehavior data = unlike.getData();
            if (data != null && data.getType() == 0){
                isnulike = true;
                System.out.println("查询到不喜欢记录");
            }
        }

//        查询收藏记录
        if (user != null){
            LambdaQueryWrapper<ApCollection> query = new LambdaQueryWrapper();
            query.eq(ApCollection::getArticleId,dto.getArticleId());
            query.eq(ApCollection::getEntryId,user.getUserId());
            ApCollection one = collectionService.getOne(query);
            if (one != null){
                iscollection = true;
                System.out.println("查询到收藏记录");
            }
        }
//        关注记录
        if (user != null){
            FollowBehaviorDto followBehaviorDto  = new FollowBehaviorDto();
            followBehaviorDto.setUserId(user.getUserId());
            ApAuthor apAuthor = apAuthorService.getById(dto.getAuthorId());
            followBehaviorDto.setFollowId(apAuthor.getUserId());
            ResponseResult<ApUserFollow> follow = userFeign.getFollow(followBehaviorDto);
            if (follow.getCode().equals(AppHttpCodeEnum.SUCCESS.getCode())){
                ApUserFollow data = follow.getData();
                if (data != null){
                    isfollow = true;
                    System.out.println("查询到关注记录");
                }
            }
        }


//        固定返回
        Map<String,Boolean> map = new HashMap<>();
        map.put("isfollow",isfollow);
        map.put("islike",islike);
        map.put("isnulike",isnulike);
        map.put("iscollection",iscollection);
        return ResponseResult.okResult(map);
    }
}
